  Page({
    data: {
      params: {
        pageNum: 1,
        pageSize: 999999,
      },
      list: [],

      totalPrice: 0,

      totalShubi: 0,

      isChooseall: false, //是否全选

      chooseArr: [],


      jisuanArr: [],

      price4: 0,
      AllDiscountFee: 0

      // bookInfoIds: []
    },
    //购物车结算
    jiesuan () {

      console.log(this.data.chooseArr)

      if (this.data.chooseArr.length == 0) {
        wx.showToast({
          title: '请选择至少一本书',
          icon: 'none'
        })
        return
      }


      var bookIdstr = "";

      if  (this.data.chooseArr.length == 1) {
        bookIdstr = this.data.chooseArr[0].bookId + '_' + this.data.chooseArr[0].bookQuality
      }else{
        for (var i = 0;i< this.data.chooseArr.length;i++) {
          bookIdstr += this.data.chooseArr[i].bookId + '_' + this.data.chooseArr[i].bookQuality + ','
        }
      }


      console.log(bookIdstr)

      console.log(this.data.chooseArr.length)


      // return


      if (this.data.fromType == 3) {
        wx.navigateTo({
          url: '/package/index/pages/buyBook/buyBook?bookArr=' + encodeURIComponent(JSON.stringify(this.data.chooseArr)) + '&shopCar=1&bookIdstr=' + bookIdstr + '&fromType=3',
        })

        return
      }
      wx.navigateTo({
        url: '/package/index/pages/buyBook/buyBook?bookArr=' + encodeURIComponent(JSON.stringify(this.data.chooseArr)) + '&shopCar=1&bookIdstr=' + bookIdstr,
      })

    },

    //书本详情
    bookdetail(e) {
      console.log(e)
      var bookId = e.currentTarget.dataset.bookid
      wx.navigateTo({
        url: '/package/index/pages/bookdetail/bookdetail?bookId=' + bookId + '&fromType=1',
      })
    },


    getList (params) {
        var _this  = this
        wx.request({
          url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxShoppingTrolleys/list/auth',
          data: params,
          method: 'POST',
          header: {
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
          "token" : wx.getStorageSync('token'),
            "uid" : wx.getStorageSync('uuid')
          },
          success: (res) => {
            console.log(typeof res.data.data)

            console.log(typeof res.data.data)


            if (res.data.code == 200) {
              var arr = []

              if (res.data.data.resultList.length !=0){
              res.data.data.resultList.forEach(function (item,index) {
                item.chooseStatus = false
                for (var i = 0; i < item.trolleysBookInfos.length;i++) {
                  item.trolleysBookInfos[i].ischoose = false
                 }

                 arr.push(item)

              })
            }

              _this.setData({
                list: arr
              })

              console.log(this.data.list)

            }else{
              wx.showToast({
                title: res.data.msg,
                icon: 'none'
              })
            }
          }
        })
    },

    changeData2 (params) {

      var arr = this.data.list

      arr[0].trolleysBookInfos.unshift(params)
      // arr[0].trolleysBookInfos.forEach(function (item,index) {

      // })

      this.setData({
        list:arr
      })
    },

    //选择书本
  chooseBook (e) {

    var _this = this
    console.log(e.currentTarget.dataset.bookid)

    console.log(e.currentTarget.dataset.bookprice)

    var bookid = e.currentTarget.dataset.bookid


    var shopid = e.currentTarget.dataset.shopid




    var jisuanArr = _this.data.jisuanArr

    jisuanArr.push(shopid)


    var price = e.currentTarget.dataset.bookprice


    _this.getShubi(_this.data.jisuanArr, shopid, price)
  //  this.data.list.forEach(function (item,index) {
  //    for (var i = 0; i < item.trolleysBookInfos.length;i++) {
  //      if (bookid == item.trolleysBookInfos[i].id) {

  //        var arr = _this.data.chooseArr

  //        var jisuanArr = _this.data.jisuanArr

  //        jisuanArr.push(item.trolleysBookInfos[i].id)

  //        arr.push({
  //          bookId: item.trolleysBookInfos[i].bookInfoId,
  //          coverPic: item.trolleysBookInfos[i].bookInfoCoverPic,
  //          name: item.trolleysBookInfos[i].bookInfoName,
  //          price: item.trolleysBookInfos[i].price
  //        })

  //        var ischoose = "list[" + index +"].trolleysBookInfos["+ i +"].ischoose"



  //        var price = _this.data.totalPrice

  //        var price2 = e.currentTarget.dataset.bookprice

  //       //  price += price2

  //       var price3 = _this.accAdd(price,price2)

  //        _this.setData({
  //          [ischoose]: true,
  //          totalPrice: price3,
  //          chooseArr: arr,
  //          jisuanArr: jisuanArr
  //        })

  //        _this.getShubi(_this.data.jisuanArr, shopid, price)

  //      }
  //    }
  //  })
  },

  // 取消选择

  cutChoose (e) {

    var _this = this
    console.log(e.currentTarget.dataset.bookid)
    console.log(e.currentTarget.dataset.bookprice)

    var bookid = e.currentTarget.dataset.bookid

    var shopid = e.currentTarget.dataset.shopid

    var jisuanArr = this.data.jisuanArr

    var arr = this.data.chooseArr


    this.data.list.forEach(function (item, index) {
      for (var i = 0; i < item.trolleysBookInfos.length; i++) {
        if (shopid == item.trolleysBookInfos[i].id) {
          

          var ischoose = "list[" + index + "].trolleysBookInfos[" + i + "].ischoose"
          _this.setData({
            [ischoose]: false
          })

          // _this.data.list[index].trolleysBookInfos[i].ischoose = false

        }
      }
    })


    for (var i = 0; i < this.data.chooseArr.length; i++) {

      if (shopid == this.data.chooseArr[i].shopid) {
        arr.splice(i, 1)

        _this.setData({
          chooseArr: arr,
          isChooseall: false
        })
      }
    }


    for (var i = 0; i < this.data.jisuanArr.length; i++) {

      if (shopid == this.data.jisuanArr[i]) {

        jisuanArr.splice(i, 1)

        if (jisuanArr.length != 0) {
          
          _this.getShubi(jisuanArr)
        }else{
          _this.setData({
            jisuanArr: [],
            chooseArr: [],
            price4: 0,
            scoreDiscount: 0,
            totalShubi: 0,
            discountFee: 0,
            AllDiscountFee: 0,
            isChooseall: false
          })


          return
        }
        

        // jisuanArr.splice(i, 1)
        
      }
    }


  


   


    // if (jisuanArr.length != 0) {

      
    //   _this.setData({
    //     jisuanArr: jisuanArr,
    //     chooseArr: arr,
    //     isChooseall: false
    //   })



    //   console.log(this.data.jisuanArr)

    //   console.log(shopid)

    //   for (var i = 0; i < _this.data.jisuanArr.length; i++) {

    //     if (shopid == _this.data.jisuanArr[i]) {

    
    //       _this.getShubi(_this.data.jisuanArr)
    //     }
    //   }

      
    // } else {
    //   _this.setData({
    //     jisuanArr: [],
    //     chooseArr: [],
    //     price4: 0,
    //     scoreDiscount: 0,
    //     totalShubi: 0,
    //     discountFee: 0,
    //     AllDiscountFee: 0,
    //     isChooseall: false
    //   })
    // }
  },


  //全选

  allChoose () {

    var _this = this

    var arr = []

    var jisuanArr = []

    this.data.list.forEach(function (item,index) {

      for (var i = 0; i < item.trolleysBookInfos.length; i++) {
        jisuanArr.push(item.trolleysBookInfos[i].id)
        arr.push({
          shopid: item.trolleysBookInfos[i].id,
          bookId: item.trolleysBookInfos[i].bookInfoId,
          coverPic: item.trolleysBookInfos[i].bookInfoCoverPic,
          name: item.trolleysBookInfos[i].bookInfoName,
          bookQuality: item.trolleysBookInfos[i].bookQuality,
          price: item.trolleysBookInfos[i].price
        })
      }

    })


 

    _this.getShubi2(jisuanArr,'quanxuan').then((res)=>{
      console.log(res)
      if (res.data.code == 200) {
        wx.hideLoading()
        if (res.data.data == "") {
          wx.showToast({
            title: '无法全选,部分书库存不足',
            icon:'none'
          })

          // return
        }else{
          _this.setData({
            totalShubi: res.data.data.suPrice,
            price4: res.data.data.price,
            scoreDiscount: res.data.data.scoreDiscount,
            discountFee: res.data.data.discountFee,
            AllDiscountFee: res.data.data.AllDiscountFee,
            totalPrice: 0,
            isChooseall: true,
            chooseArr: arr,
            jisuanArr: jisuanArr
          })
          var price = _this.data.totalPrice

          _this.data.list.forEach(function (item, index) {
            for (var i = 0; i < item.trolleysBookInfos.length; i++) {

              var ischoose = "list[" + index + "].trolleysBookInfos[" + i + "].ischoose"
              _this.setData({
                [ischoose]: true
              })
              price += _this.accAdd(0, item.trolleysBookInfos[i].price)
            }
          })

          _this.setData({
            totalPrice: price
          })  

        }
      }
    })


   

  },

  // 取消全选

  cutAllchoose () {

    var _this = this

    var arr = []
    var jisuanArr = []
    this.setData({
      totalShubi: 0,
      totalPrice: 0,
      isChooseall: false,
      chooseArr: arr,
      jisuanArr: jisuanArr
    })


    this.data.list.forEach(function (item, index) {
      for (var i = 0; i < item.trolleysBookInfos.length; i++) {
        var ischoose = "list[" + index + "].trolleysBookInfos[" + i + "].ischoose"
        _this.setData({
          [ischoose]: false,
          jisuanArr: [],
          chooseArr: [],
          price4: 0,
          scoreDiscount: 0,
          totalShubi: 0,
          discountFee: 0,
          AllDiscountFee: 0
        })
      }
    })


  },

  // 选择一块
  // chooseItem (e) {
  //   console.log(e)

  //   var bookIndex = e.currentTarget.dataset.bookindex

  //   var ischoose = "list[" + bookIndex + "].chooseStatus"

  //   this.setData({
  //     [ischoose]: true
  //   })

  //   for (var i = 0; i < this.data.list[bookIndex].trolleysBookInfos.length; i++) {

  //   }
  // },


  //加法
 accAdd(arg1, arg2){
     var r1, r2, m;
     try{ r1=arg1.toString().split(".")[1].length }catch(e) { r1 = 0 } 
 try{ r2=arg2.toString().split(".")[1].length }catch(e) { r2 = 0 } 
 m=Math.pow(10, Math.max(r1, r2)) 
 return(arg1*m+ arg2 * m) / m 
 },

  // 剑法
  Subtr(arg1, arg2){
    var r1, r2, m, n;
    try{ r1=arg1.toString().split(".")[1].length }catch(e) { r1 = 0 }
     try{ r2=arg2.toString().split(".")[1].length }catch(e) { r2 = 0 }
     m=Math.pow(10, Math.max(r1, r2));
    n=(r1 >= r2) ? r1 : r2;
    return((arg1 * m - arg2 * m) / m).toFixed(n);
 },

onLoad (options) {
  this.getList(this.data.params)
  console.log('options.fromType ====' + options.fromType)
  if (options.fromType) {
    this.setData({
      fromType: options.fromType
    })
  }
},
onShow () {

},

payOrder () {
  this.setData({
    chooseArr: [],
    totalPrice: 0,
    isChooseall: false,
  })
  this.getList(this.data.params)
},

  //删除购物车
  deleteCar (e) {
    console.log(e)
    var carid = e.currentTarget.dataset.carid
    console.log(carid)
    // return
    var price = e.currentTarget.dataset.bookprice

    var id2 = e.currentTarget.dataset.bookid
    var _this = this
    wx.showModal({
      title: '删除',
      content: '是否删除此商品',
      success: function (res) {
        if (res.confirm) {
          _this.deleteCarApi(carid,price,id2)
        }else{
          return false
        }
      }
    })

  },

    //删除购物车api
    deleteCarApi(id, price2, id2) {
      console.log('total---------' + this.data.totalPrice)
      console.log('price2-----' + price2)
      // return
      var _this = this
      var params = {
        ids: id
      }
      wx.request({
        url:
          'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxShoppingTrolleys/del/auth',
        data: params,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          token: wx.getStorageSync('token'),
          uid: wx.getStorageSync('uuid')
        },
        success: res => {
          if (res.data.code == 200) {
            wx.showToast({
              title: '删除成功',
              icon: 'none'
            })
            
            
            if (_this.data.fromType == 3) {
              var pages = getCurrentPages();//获取页面栈
              var beforePage = pages[pages.length - 2];

              beforePage.changeData8() 
            }

            var list = _this.data.list

            var arr = _this.data.chooseArr
            var jisuanArr = _this.data.jisuanArr

            list.forEach(function (item, index) {
              for (var i = 0; i < item.trolleysBookInfos.length; i++) {
                if (id == item.trolleysBookInfos[i].id) {
                  list[index].trolleysBookInfos.splice(i, 1)
                  _this.setData({
                    list:list
                  })
                }
              }
            })


            for (var i = 0; i < _this.data.jisuanArr.length; i++) {

              if (id == _this.data.jisuanArr[i]) {
                jisuanArr.splice(i, 1)

                if (jisuanArr.length!=0) {
                  _this.getShubi(jisuanArr)
                }
              }
            }


            for (var i = 0; i < _this.data.chooseArr.length; i++) {

              if (id == _this.data.chooseArr[i].shopid) {
                arr.splice(i, 1)
              }
            }




            if (jisuanArr.length != 0) {
              _this.setData({
                jisuanArr: jisuanArr,
                chooseArr: arr
              })


              if (jisuanArr.length== _this.data.list[0].trolleysBookInfos.length) {
                _this.setData({
                  isChooseall: true
                })
              }

            } else {
              _this.setData({
                jisuanArr: [],
                chooseArr: [],
                price4: 0,
                scoreDiscount: 0,
                totalShubi: 0,
                discountFee: 0,
                AllDiscountFee: 0,
                isChooseall: false
              })
            }



          }
        }
      })
    },

    changeData () {
      this.getList(this.data.params)

      this.setData({
        jisuanArr: [],
        chooseArr: [],
        price4: 0,
        scoreDiscount: 0,
        totalShubi: 0,
        discountFee: 0,
        AllDiscountFee: 0
      })
    },  



    getShubi2(bookInfoIds, shopid, pricenum) {
      console.log(bookInfoIds)


      return new Promise((resolve, reject) => {
      var _this = this
      wx.showLoading({
        title: "计算中",
        icon: "none"
      })
      var params = {
        shoppIds:
          bookInfoIds.length == 1 ? bookInfoIds[0] : bookInfoIds.join(',')
      }

      wx.request({
        url: 'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxShoppingTrolleys/score/discounts/auth',
        data: params,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          token: wx.getStorageSync('token'),
          uid: wx.getStorageSync('uuid')
        },
        success: (res)=>{
          resolve(res)
        }
      })

      })
    },


    getShubi(bookInfoIds, shopid, pricenum) {
      // wx.showToast({
      //   title: shopid,
      // })
      console.log(bookInfoIds)
      var _this = this
      wx.showLoading({
        title: "计算中",
        icon: "none"
      })
      var params = {
        shoppIds:
          bookInfoIds.length == 1 ? bookInfoIds[0] : bookInfoIds.join(',')
      }
      wx.request({
        url:
          'https://devapi.xiaoshitimebank.com/user/sdx/sdx/sdxShoppingTrolleys/score/discounts/auth',
        data: params,
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
          token: wx.getStorageSync('token'),
          uid: wx.getStorageSync('uuid')
        },
        success: res => {
          if (res.data.code == 200) {

            wx.hideLoading()

            if (res.data.data == "") {
              wx.showToast({
                title: shopid == "quanxuan"?"无法全选,部分书库存不足":"此书已无库存",
                icon: "none"
              })



              var jisuanArr = _this.data.jisuanArr

              for (var i = 0; i < jisuanArr.length; i++) {
                if (shopid == jisuanArr[i]) {
                  jisuanArr.splice(i, 1)


                  _this.setData({
                    jisuanArr: jisuanArr
                  })
                }
              }


              return false
            }

            _this.data.list.forEach(function (item, index) {
              for (var i = 0; i < item.trolleysBookInfos.length; i++) {
                if (shopid == item.trolleysBookInfos[i].id) {

                  var ischoose = "list[" + index + "].trolleysBookInfos[" + i + "].ischoose"
                  var arr = _this.data.chooseArr

                  arr.push({
                    bookId: item.trolleysBookInfos[i].bookInfoId,
                    coverPic: item.trolleysBookInfos[i].bookInfoCoverPic,
                    name: item.trolleysBookInfos[i].bookInfoName,
                    price: item.trolleysBookInfos[i].price,
                    bookQuality: item.trolleysBookInfos[i].bookQuality,
                    shopid: item.trolleysBookInfos[i].id
                  })

                  // var ischoose =
                  //   'list[' + index + '].trolleysBookInfos[' + i + '].ischoose'
                  // _this.data.list[index].trolleysBookInfos[i].ischoose = true

                  var price = _this.data.totalPrice

                  var price2 = pricenum

                  //  price += price2

                  var price3 = _this.accAdd(price, price2)

                  _this.setData({
                    [ischoose]: true,
                    totalPrice: price3,
                    chooseArr: arr,
                    jisuanArr: bookInfoIds
                  }) 

                }
              }
            })





            if (bookInfoIds.length == _this.data.list[0].trolleysBookInfos.length) {
              _this.setData({
                isChooseall: true
              })
            }

            _this.setData({
              totalShubi: res.data.data.suPrice,
              price4: res.data.data.price,
              scoreDiscount: res.data.data.scoreDiscount,
              discountFee: res.data.data.discountFee,
              AllDiscountFee: res.data.data.AllDiscountFee
            })
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: 'none'
            })
          }
        }
      })
    }
})
